<template>
  <div class="houtai">
    <el-tabs v-model="activeTab" type="card">
      <!-- 用户列表 Tab -->
      <el-tab-pane label="用户列表" name="user">
        <el-table :data="userList" border style="width: 100%">
          <el-table-column
            prop="id"
            label="用户ID"
            width="80"
          ></el-table-column>
          <el-table-column prop="nickName" label="昵称"></el-table-column>
          <el-table-column prop="tel" label="手机号"></el-table-column>
          <el-table-column prop="pwd" label="密码"></el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <el-button
                size="small"
                type="warning"
                @click="openEditDialog(scope.row)"
                >编辑</el-button
              >
              <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" @click="dialogFormVisible = true"
          >新增</el-button
        >
        <el-pagination
          layout="prev, pager, next"
          :total="userTotal"
          :page-size="pageSize"
          @current-change="handleUserPageChange"
          style="margin-top: 20px; text-align: right"
        />
      </el-tab-pane>
      <el-dialog v-model="dialogFormVisible" title="新增用户" width="500">
        <el-form :model="form" label-position="right" :rules="rules">
          <el-form-item
            label="昵称"
            :label-width="formLabelWidth"
            prop="nickName"
          >
            <el-input v-model="form.nickName" autocomplete="off" />
          </el-form-item>
          <el-form-item label="手机号" :label-width="formLabelWidth" prop="tel">
            <el-input v-model="form.tel" autocomplete="off" />
          </el-form-item>
          <el-form-item label="密码" :label-width="formLabelWidth" prop="pwd">
            <el-input v-model="form.pwd" autocomplete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="addUser"> 确认 </el-button>
          </div>
        </template>
      </el-dialog>
      <el-dialog v-model="editDialogVisible" title="编辑用户" width="500">
        <el-form :model="editForm" label-position="right" :rules="rules">
          <el-form-item
            label="昵称"
            :label-width="formLabelWidth"
            prop="nickName"
          >
            <el-input v-model="editForm.nickName" autocomplete="off" />
          </el-form-item>
          <el-form-item label="手机号" :label-width="formLabelWidth" prop="tel">
            <el-input v-model="editForm.tel" autocomplete="off" disabled />
          </el-form-item>
          <el-form-item label="密码" :label-width="formLabelWidth" prop="pwd">
            <el-input v-model="editForm.pwd" autocomplete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="editDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitEdit">确认</el-button>
          </div>
        </template>
      </el-dialog>
      <!-- 商品列表 Tab -->
      <el-tab-pane label="商品列表" name="product">
        <el-table :data="goodsList" border style="width: 100%">
          <el-table-column
            prop="id"
            label="商品ID"
            width="80"
          ></el-table-column>
          <el-table-column prop="name" label="商品名称"></el-table-column>
          <el-table-column prop="num" label="库存" width="80"></el-table-column>
          <el-table-column
            prop="price"
            label="价格"
            width="100"
          ></el-table-column>
          <el-table-column label="图片" width="100">
            <template #default="{ row }">
              <a :href="row.imgUrl">
                <img :src="row.imgUrl" style="width: 50px; height: 50px" />
              </a>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="{ row }">
              <el-button
                size="small"
                type="primary"
                @click="openEditGoodsDialog(row)"
                >编辑</el-button
              >
              <el-button
                size="small"
                type="danger"
                @click="handleDeleteGoods(row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" @click="addGoodsDialogVisible = true"
          >新增</el-button
        >
        <el-pagination
          layout="prev, pager, next"
          :total="productTotal"
          :page-size="pageSize"
          style="margin-top: 20px; text-align: right"
        />
      </el-tab-pane>
      <el-dialog v-model="addGoodsDialogVisible" title="新增商品" width="500">
        <el-form
          :model="addGoodsForm"
          label-position="right"
          :rules="goodsRules"
        >
          <el-form-item
            label="商品名称"
            :label-width="formLabelWidth"
            prop="name"
          >
            <el-input v-model="addGoodsForm.name" autocomplete="off" />
          </el-form-item>
          <el-form-item label="库存" :label-width="formLabelWidth" prop="num">
            <el-input-number v-model="addGoodsForm.num" :min="0" />
          </el-form-item>
          <el-form-item label="价格" :label-width="formLabelWidth" prop="price">
            <el-input-number
              v-model="addGoodsForm.price"
              :step="0.01"
              :min="0"
            />
          </el-form-item>
          <el-form-item
            label="图片地址"
            :label-width="formLabelWidth"
            prop="imgUrl"
          >
            <el-input v-model="addGoodsForm.imgUrl" autocomplete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="addGoodsDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitAddGoods">确认</el-button>
          </div>
        </template>
      </el-dialog>
      <el-dialog v-model="editGoodsDialogVisible" title="编辑商品" width="500">
        <el-form
          :model="editGoodsForm"
          label-position="right"
          :rules="goodsRules"
        >
          <el-form-item
            label="商品名称"
            :label-width="formLabelWidth"
            prop="name"
          >
            <el-input v-model="editGoodsForm.name" autocomplete="off" />
          </el-form-item>
          <el-form-item label="库存" :label-width="formLabelWidth" prop="num">
            <el-input-number v-model="editGoodsForm.num" :min="0" />
          </el-form-item>
          <el-form-item label="价格" :label-width="formLabelWidth" prop="price">
            <el-input-number
              v-model="editGoodsForm.price"
              :step="0.01"
              :min="0"
            />
          </el-form-item>
          <el-form-item
            label="图片地址"
            :label-width="formLabelWidth"
            prop="imgUrl"
          >
            <el-input v-model="editGoodsForm.imgUrl" autocomplete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="editGoodsDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitEditGoods">确认</el-button>
          </div>
        </template>
      </el-dialog>
      <!-- 订单列表 Tab -->
       <el-tab-pane label="订单列表" name="order">
        <el-table :data="orderList" border style="width: 100%">
          <el-table-column
            prop="order_id"
            label="订单ID"
            width="200"
          ></el-table-column>
          <el-table-column prop="goods_name" label="商品名称"></el-table-column>
          <el-table-column
            prop="goods_price"
            label="总价格"
            width="100"
          ></el-table-column>
          <el-table-column prop="goods_num" label="数量" width="80"></el-table-column>
          <el-table-column prop="order_status" label="订单状态" width="80"></el-table-column>
          <el-table-column prop="uId" label="用户ID" width="100"></el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="{ row }">
              <el-button
                size="small"
                type="primary"
                @click="openEditOrderDialog(row)"
                >编辑</el-button
              >
              <el-button
                size="small"
                type="danger"
                @click="handleDeleteGoods(row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" @click="addGoodsDialogVisible = true"
          >新增</el-button
        >
        <el-pagination
          layout="prev, pager, next"
          :total="productTotal"
          :page-size="pageSize"
          style="margin-top: 20px; text-align: right"
        />
      </el-tab-pane>
      <el-dialog v-model="addGoodsDialogVisible" title="新增商品" width="500">
        <el-form
          :model="addGoodsForm"
          label-position="right"
          :rules="goodsRules"
        >
          <el-form-item
            label="商品名称"
            :label-width="formLabelWidth"
            prop="name"
          >
            <el-input v-model="addGoodsForm.name" autocomplete="off" />
          </el-form-item>
          <el-form-item label="库存" :label-width="formLabelWidth" prop="num">
            <el-input-number v-model="addGoodsForm.num" :min="0" />
          </el-form-item>
          <el-form-item label="价格" :label-width="formLabelWidth" prop="price">
            <el-input-number
              v-model="addGoodsForm.price"
              :step="0.01"
              :min="0"
            />
          </el-form-item>
          <el-form-item
            label="图片地址"
            :label-width="formLabelWidth"
            prop="imgUrl"
          >
            <el-input v-model="addGoodsForm.imgUrl" autocomplete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="addGoodsDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitAddGoods">确认</el-button>
          </div>
        </template>
      </el-dialog>
      <el-dialog v-model="editOrderDialogVisible" title="编辑订单" width="500">
        <el-form
          :model="editGoodsForm"
          label-position="right"
          :rules="goodsRules"
        >
          <el-form-item
            label="商品名称"
            :label-width="formLabelWidth"
            prop="name"
          >
            <el-input v-model="editGoodsForm.name" autocomplete="off" />
          </el-form-item>
          <el-form-item label="库存" :label-width="formLabelWidth" prop="num">
            <el-input-number v-model="editGoodsForm.num" :min="0" />
          </el-form-item>
          <el-form-item label="价格" :label-width="formLabelWidth" prop="price">
            <el-input-number
              v-model="editGoodsForm.price"
              :step="0.01"
              :min="0"
            />
          </el-form-item>
          <el-form-item
            label="图片地址"
            :label-width="formLabelWidth"
            prop="imgUrl"
          >
            <el-input v-model="editGoodsForm.imgUrl" autocomplete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="editOrderDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitEditGoods">确认</el-button>
          </div>
        </template>
      </el-dialog>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";

import http from "@/common/api/request.js";
import { reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
const dialogFormVisible = ref(false);
const formLabelWidth = "80px";
const rules = {
  nickName: [{ required: true, message: "请输入昵称", trigger: "blur" }],
  tel: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[23456789]\d{9}$/,
      message: "手机号格式不正确",
      trigger: "blur",
    },
  ],
  pwd: [{ required: true, message: "请输入密码", trigger: "blur" }],
};
const form = reactive({
  nickName: "",
  tel: "",
  pwd: "",
});
const addUser = () => {
  dialogFormVisible.value = false;
  http
    .$axios({
      url: "/api/register",
      method: "POST",
      data: {
        phone: form.tel,
        pwd: form.pwd,
        nickName: form.nickName,
      },
    })
    .then(() => {
      ElMessage({
        message: "新增成功",
        type: "success",
      });
      fetchUserData();
    });
};

// 编辑用户相关
const editDialogVisible = ref(false);
const editForm = reactive({
  id: "",
  nickName: "",
  tel: "",
  pwd: "",
});

// 打开编辑对话框并填充数据
const openEditDialog = (row) => {
  Object.assign(editForm, row);
  editDialogVisible.value = true;
};

// 提交编辑表单
const submitEdit = async () => {
  try {
    await http.$axios({
      url: "/api/modify",
      method: "POST",
      data: {
        id: editForm.id,
        nickName: editForm.nickName,
        phone: editForm.tel,
        pwd: editForm.pwd,
      },
    });
    ElMessage({
      message: "修改成功",
      type: "success",
    });
    editDialogVisible.value = false;
    fetchUserData(); // 刷新用户列表
  } catch (error) {
    ElMessage.error("修改失败");
  }
};

// 删除用户
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm("确定要删除该用户吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    await http.$axios({
      url: "/api/delete",
      method: "POST",
      data: {
        id: row.id,
      },
    });

    ElMessage.success("删除成功");
    fetchUserData(); // 刷新用户列表
  } catch (error) {
    ElMessage.error("删除失败");
  }
};

onMounted(() => {
  fetchUserData();
  fetchData();
  fetchOrderData();
});
const userList = ref([]);
const goodsList = ref([]);
const orderList = ref([]);

const fetchUserData = async () => {
  let res = await http.$axios({ url: "/api/getUserInfo" });
  console.log(res);
  userList.value = res;
};
const fetchData = async () => {
  let res = await http.$axios({ url: "/api/goods_list" });
  productTotal.value = goodsList.value.length;
  console.log(res);
  goodsList.value = res;
};
const fetchOrderData = async () => { 
  let res = await http.$axios({ url: "/api/order_list" });
  orderTotal.value = orderList.value.length;
  console.log(res,'res');
  orderList.value = res;
};
// 当前激活 tab
const activeTab = ref("user");

// 分页配置
const pageSize = 10;

// 用户列表数据
// const userList = ref([])
const userTotal = ref(0);

// 商品列表数据
const productTotal = ref(0);
// 订单列表数据
const orderTotal = ref(0);
// 切换分页 - 用户
const handleUserPageChange = (page) => {
  fetchUsers(page);
};

const addGoodsDialogVisible = ref(false);
const addGoodsForm = reactive({
  name: "",
  num: 0,
  price: 0,
  imgUrl: "",
});

// 表单校验规则（可选）
const goodsRules = {
  name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  num: [{ required: true, message: "请输入库存数量", trigger: "blur" }],
  price: [{ required: true, message: "请输入价格", trigger: "blur" }],
  imgUrl: [{ required: true, message: "请输入图片地址", trigger: "blur" }],
};

// 提交新增商品
const submitAddGoods = async () => {
  try {
    await http.$axios({
      url: "/api/addGoods",
      method: "POST",
      data: {
        name: addGoodsForm.name,
        num: addGoodsForm.num,
        price: addGoodsForm.price,
        imgUrl: addGoodsForm.imgUrl,
      },
    });

    ElMessage.success("新增成功");
    addGoodsDialogVisible.value = false;
    fetchData(); // 刷新商品列表
  } catch (error) {
    ElMessage.error("新增失败");
  }
};

const editGoodsForm = reactive({
  id: "",
  name: "",
  num: 0,
  price: 0,
  imgUrl: "",
});
const editGoodsDialogVisible = ref(false);
const editOrderDialogVisible = ref(false);
// 打开编辑商品对话框并填充数据
const openEditGoodsDialog = (row) => {
  Object.assign(editGoodsForm, row);
  editGoodsDialogVisible.value = true;
};
const openEditOrderDialog = (row) => {
  Object.assign(editGoodsForm, row);
  editOrderDialogVisible.value = true;
};
// 提交编辑商品
const submitEditGoods = async () => {
  try {
    await http.$axios({
      url: "/api/editGoods",
      method: "POST",
      data: {
        id: editGoodsForm.id,
        name: editGoodsForm.name,
        num: editGoodsForm.num,
        price: editGoodsForm.price,
        imgUrl: editGoodsForm.imgUrl,
      },
    });

    ElMessage.success("编辑成功");
    editGoodsDialogVisible.value = false;
    fetchData(); // 刷新商品列表
  } catch (error) {
    ElMessage.error("编辑失败");
  }
};
// 删除商品
const handleDeleteGoods = async (row) => {
  try {
    await ElMessageBox.confirm("确定要删除该商品吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    await http.$axios({
      url: "/api/deleteGoods",
      method: "POST",
      data: {
        id: row.id,
      },
    });
    fetchData(); // 刷新商品列表
    ElMessage.success("删除成功");
  } catch (error) {
    ElMessage.error("删除失败");
  }
};
</script>

<style scoped>
.houtai {
  padding: 20px;
  background-color: #f5f7fa;
}
</style>
